package com.yk.controller;

import cn.hutool.core.util.ObjectUtil;
import com.yk.lb.MyLoadBalance;
import com.yk.pojo.CommonResult;
import com.yk.pojo.Payment;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import javax.annotation.Resource;
import java.net.URI;
import java.util.List;

@RestController
public class PaymentController {
    private static final Logger logger = LoggerFactory.getLogger(PaymentController.class);

//    public static final String URL = "http://localhost:8001";
    public static final String URL = "http://CLOUD-PAYMENT-SERVICE";

    @Resource
    private MyLoadBalance myLoadBalance;
    @Autowired
    RestTemplate restTemplate;

    @Resource
    DiscoveryClient discoveryClient;

    @GetMapping("/consumer/create")
    public CommonResult create(Payment payment) {
        return this.restTemplate.postForObject(URL + "/payment/create", payment, CommonResult.class);
    }

    @GetMapping("/consumer/get/{id}")
    public CommonResult get(@PathVariable int id) {
        return this.restTemplate.getForObject(URL + "/payment/get/" + id, CommonResult.class);
    }

    @GetMapping("/consumer/all")
    public CommonResult all() {
        return this.restTemplate.getForObject(URL + "/payment/all", CommonResult.class);
    }

    @GetMapping("/consumer/all1")
    public CommonResult all1() {

        ResponseEntity<CommonResult> resultResponseEntity = this.restTemplate.getForEntity(URL + "/payment/all", CommonResult.class);
        if (resultResponseEntity.getStatusCode().is2xxSuccessful()) {
            return resultResponseEntity.getBody();
        }else{
            return new CommonResult<>(444, "操作错误", "");
        }

    }

    @GetMapping("/consumer/lb")
    public Object paymentLb() {
        List<ServiceInstance> instances = discoveryClient.getInstances("CLOUD-PAYMENT-SERVICE");
        ServiceInstance instance = myLoadBalance.instances(instances);

        if (ObjectUtil.isNotNull(instance)) {
            URI uri = instance.getUri();
            String forObject = restTemplate.getForObject(uri + "/payment/lb", String.class);
            return new CommonResult<>(200, "操作成功", forObject);
        }else{
            return new CommonResult<>(444, "操作错误", "");
        }


    }



}
